package com.ren.weibo.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ren.weibo.base.response.JsonResult;
import com.ren.weibo.base.response.StatusCode;
import com.ren.weibo.mapper.WeiboMapper;
import com.ren.weibo.pojo.dto.WeiboParam;
import com.ren.weibo.pojo.entity.Weibo;
import com.ren.weibo.pojo.vo.UserVO;
import com.ren.weibo.pojo.vo.WeiboDetailVO;
import com.ren.weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Validated
@Slf4j
@RestController
@RequestMapping("/v1/weibo")
@Api(tags = "微博模块")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @ApiOperation("发布微博")
    @ApiOperationSupport(order = 10)
    @PostMapping("/insert")
    public JsonResult insert(@RequestBody WeiboParam weiboParam, @ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");

        Weibo weibo = new Weibo();
        String content = weiboParam.getContent();
        weibo.setContent(content);
        weibo.setCreateTime(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.add(weibo);
        return JsonResult.ok();
    }

    @ApiOperation("微博首页列表")
    @ApiOperationSupport(order = 20)
    @GetMapping("/selectIndex")
    public JsonResult selectIndex() {
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable index = ops.get("weibo_index");
        if (index != null) {
            return JsonResult.ok(index);
        }
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
        ops.set("weibo_index", (Serializable) weiboIndexVOS, 30, TimeUnit.SECONDS);
        return new JsonResult(StatusCode.OPERATION_SUCCESS, weiboIndexVOS);
    }

    @ApiOperation("微博详情")
    @ApiOperationSupport(order = 30)
    @GetMapping("/selectById")
    public JsonResult selectById(@Size(min = 1, max = 100, message = "微博ID长度必须在1到100之间") Integer id) {
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        return new JsonResult(StatusCode.OPERATION_SUCCESS, weiboDetailVO);
    }
}
